<template>
  <div style="position: relative">
    <div style="padding: 20px ">
      <h6>班次设置</h6>
      <div style="padding-bottom: 20px ">
        <span class="title1">白班时间</span>
        <template>
           <el-time-picker
             value-format="HH:mm:ss"
              is-range
              v-model="timeParams.dayTime"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围">
            </el-time-picker>
        </template>
      </div>
      <div>
        <span class="title1">夜班时间</span>
        <template>
          <el-time-picker
          is-range
          value-format="HH:mm:ss"
          v-model="timeParams.nightTime"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="选择时间范围">
        </el-time-picker>
        </template>
      </div>
    </div>
    <div style="padding: 20px 20px 0 20px">
      <el-switch
        @change="handleChangeIsAuto"
        :value="autoData.isAuto"
        active-text="自动班结"
      >
      </el-switch>
    </div>
    <div class="station_box" ref="stationBox" v-if="autoData.isAuto">
      <template >
        <el-form
          v-for="(item, index) in autoData.automaticClassInfos"
          :rules="automaticClassInfosRules"
          :key="index"
          ref="form"
          :model="item"
          label-width="80px"
          label-position="left"
          size="mini"
        >
          <div class="station_item">
            <div class="left_item">
              <p class="title">选择油站</p>
              <el-form-item label="油站名称" prop="stationId">
                <el-select v-model="item.stationId" placeholder="请选择">
                  <el-option
                    v-for="item in stationList"
                    :key="item.stationId"
                    :label="item.stationName"
                    :value="item.stationId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <p class="title">每天班结时间设置</p>
              <el-form-item
                label-width="100px"
                v-for="(dateItem, dateIndex) in item.dateList"
                :key="dateIndex"
              >
                <span class="t" slot="label">班结时间{{ dateIndex + 1 }}</span>
                <el-time-select
                  placeholder="请选择"
                  v-model="dateItem.time"
                  :picker-options="{
                    start: '00:00',
                    step: '01:00',
                    end: '23:00',
                  }"
                >
                </el-time-select>
                <el-button
                  v-if="item.dateList.length === dateIndex + 1"
                  class="ml8"
                  type="primary"
                  icon="el-icon-plus"
                  circle
                  @click="handleAddDate(index, dateIndex)"
                ></el-button>
                <el-button
                  class="ml8"
                  v-if="dateIndex > 0"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="handleDeleteDate(index, dateIndex)"
                ></el-button>
              </el-form-item>
            </div>
            <div class="right_item">
              <el-button
                v-if="
                  stationLen > 1 &&
                  autoData.automaticClassInfos.length === index + 1
                "
                type="primary"
                size="mini"
                @click="handleAddStation"
                >添加</el-button
              >
              <el-button
                v-if="index >= 0 && autoData.automaticClassInfos.length > 1"
                type="danger"
                size="mini"
                @click="handleDeleteStation(index)"
                >删除</el-button
              >
            </div>
          </div>
        </el-form>
      </template>
    </div>

    <div class="bottom_box">
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </div>
  </div>
</template>
<script>
import { getEnterpriseStationList } from "@/api/dept";
import { setAutomaticClass, getAutomaticClass, updateClassTime, getDayClassTime } from "@/api/station/order";
import { error } from "highcharts";
export default {
  data() {
    return {
      autoData: {
        isAuto: false,
        automaticClassInfos: [],
      },
      stationList: [],
      automaticClassInfosRules: {
        stationId: [
          { required: true, message: "请选择油站", trigger: "change" },
        ],
      },
      timeParams: {
        dayTime: null,
        nightTime: null
      }
      

    };
  },
  computed: {
    stationLen() {
      let list = [];
      if (this.stationList.length > 0) {
        list = this.stationList.filter((f) => f.status === "1");
      }
      return list.length;
    },
  },
  methods: {
    // 查询班次时间
    getDayClassTimeInfo() {
      getDayClassTime().then(res => {
        if(res) {
          const dayTimeArray = [res.dayShiftStartTime, res.dayShiftEndTime];
          const nightTimeArray = [res.nightShiftStartTime, res.nightShiftEndTime];
          this.timeParams.dayTime = dayTimeArray
          this.timeParams.nightTime = nightTimeArray
        }
      })
    },
    // 辅助函数，将时间字符串转换为以秒为单位的时间
    getTimeInSeconds(timeString) {
      const [hours, minutes, seconds] = timeString.split(':');
      return hours * 3600 + minutes * 60 + seconds;
    },
    // 查询油站
    getStationList(val) {
      getEnterpriseStationList({ enterpriseId: val }).then((res) => {
        this.stationList = res;
      });
    },
    getData(enterpriseId) {
      getAutomaticClass({ id: enterpriseId }).then((res) => {
        res.data.isAuto = !!res.data.isAuto;
        if (res.data.automaticClassInfos) {
          res.data.automaticClassInfos.forEach((item) => {
            item.dateList = [];
            item.knotTimes.forEach((timeItem) => {
              let data = {
                time: timeItem,
              };
              item.dateList.push(data);
            });
          });
        }

        this.autoData = res.data;
        if(this.autoData.automaticClassInfos === null) {
          this.autoData.automaticClassInfos = []
        }
        console.log(this.autoData);
      });
    },
    // 保存
    handleSubmit() {
      console.log(this.autoData);
      console.log(this.autoData.automaticClassInfos);
      let isDate = null;
      for (let i = 0; i < this.autoData.automaticClassInfos.length; i++) {
        let item = this.autoData.automaticClassInfos[i];
        isDate = item.dateList.every((e) => e.time);
        if (!isDate) {
          break;
        }
      }
      if (!isDate && this.autoData.isAuto) {
        return this.$message.error("班结时间不能为空");
      }
      this.$confirm("是否确认保存班结设置相关数据", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then((res) => {
       // 设置班次
      let params = {  
        "dayShiftEndTime": null,
        "dayShiftStartTime": null,
        "nightShiftEndTime": null,
        "nightShiftStartTime": null
          }


        if(!((!this.timeParams.dayTime && ! this.timeParams.nightTime) || (!!this.timeParams.dayTime && !! this.timeParams.nightTime)) ) {
          return this.$message.warning('白夜班不能单独设置')
        }
      if(this.timeParams.dayTime && this.timeParams.nightTime) {
        params.dayShiftStartTime = this.timeParams.dayTime[0]
        params.dayShiftEndTime = this.timeParams.dayTime[1]
        params.nightShiftStartTime = this.timeParams.nightTime[0]
        params.nightShiftEndTime = this.timeParams.nightTime[1]
        if (this.getTimeInSeconds(params.dayShiftStartTime ) < this.getTimeInSeconds(params.nightShiftEndTime ) && this.getTimeInSeconds(params.dayShiftEndTime ) > this.getTimeInSeconds(params.nightShiftStartTime )) {
          // 时间段存在交集
          return this.$message.warning('时间段存在交集');
        }

      }
      
      if(this.$store.state.user.userLevel !== null) {
        updateClassTime(params).then(res => {
          if (res && res.code === 200) {
                this.$message.success(res.msg);
              } else {
                this.$message.error(res.msg);
              }
        })
      }


        if (this.autoData.isAuto) {
          let dateList = [];
          this.autoData.automaticClassInfos.forEach((item) => {
            item.dateList.forEach((date) => {
              if (date.time != "") {
                date.time = date.time;
                dateList.push(date.time);
              }
            });
            item.knotTimes = dateList;
            dateList = [];
          });
        }
        let autoData = JSON.parse(JSON.stringify(this.autoData));
        autoData.isAuto = autoData.isAuto ? 1 : 0;
        console.log(autoData);
        if (
          autoData.automaticClassInfos &&
          this.stationIdSet(autoData.automaticClassInfos)
        ) {
          setAutomaticClass(autoData).then((res) => {
            console.log(res);
            if (res && res.code === 200) {
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          this.$message.error("请删除重复油站！！！");
        }
      });
    },
    stationIdSet(automaticClassInfos) {
      const newArr = automaticClassInfos.map((item) => item.stationId);
      const arrSet = new Set(newArr);
      return arrSet.size == newArr.length;
    },
    handleChangeIsAuto(val) {
      console.log(val);
      if (!val) {
        this.$confirm(
          "是否确认关闭，关闭之后再开启班结设置数据将初始化！！！",
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).then((res) => {
          if (val) {
            this.autoData = {
              isAuto: true,
              automaticClassInfos: [
                {
                  stationId: "",
                  dateList: [
                    {
                      time: "",
                    },
                  ],
                },
              ],
            };
          } else {
            this.autoData = {
              isAuto: false,
              automaticClassInfos: [],
            };
          }
        });
      } else {
        if (val) {
          this.autoData = {
            isAuto: true,
            automaticClassInfos: [
              {
                stationId: "",
                dateList: [
                  {
                    time: "",
                  },
                ],
              },
            ],
          };
        } else {
          this.autoData = {
            isAuto: false,
            automaticClassInfos: [],
          };
        }
      }


    },
    
    /**
     * 添加油站块
     */
    handleAddStation() {
      this.autoData.automaticClassInfos.push({
        stationId: "",
        dateList: [
          {
            time: "",
          },
        ],
      });
      this.$nextTick(() => {
        let scrollEl = this.$refs.stationBox;
        scrollEl.scrollTo({ top: scrollEl.scrollHeight, behavior: "smooth" });
      });
    },
    /**
     *
     * @param {Number} index 油站块下标
     */
    handleDeleteStation(index) {
      this.autoData.automaticClassInfos.splice(index, 1);
    },
    /**
     *
     * @param {Number} index 油站块下标
     * @param {Number} dateIndex 班结时间数组下标
     */
    handleAddDate(index, dateIndex) {
      if (dateIndex === 4)
        return this.$message.error("每个油站最多添加五个班结时间！！！");
      console.log(dateIndex);
      this.autoData.automaticClassInfos[index].dateList.push({
        time: "",
      });
    },
    /**
     *
     * @param {Number} index 油站块下标
     * @param {Number} dateIndex 班结时间数组下标
     */
    handleDeleteDate(index, dateIndex) {
      this.autoData.automaticClassInfos[index].dateList.splice(dateIndex, 1);
    },
    
  },
  created() {
    if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
      this.getData(this.presentEnterprise.enterpriseId);
      this.getStationList(this.presentEnterprise.enterpriseId);
    }
    this.getDayClassTimeInfo()
  },
};
</script>
<style lang="scss" scoped>
.station_box {
  display: grid;
  grid-template-columns: repeat(2, 50%);
  // grid-template-rows: repeat(10, 250px);
  grid-row-gap: 20px;
  grid-column-gap: 30px;
  padding: 20px;
  // margin-bottom: 60px;
  overflow-y: scroll;
  height: calc(100vh - 190px);

  .station_item {
    height: fit-content;
    margin-top: 20px;
    display: flex;
    flex-direction: row;
    position: relative;

    .left_item {
      width: 70%;
      height: fit-content;
      padding: 10px;
      border: 1px solid #333;
      border-radius: 10px;

      .title {
        display: inline-block;
        font-weight: 600;
      }
    }

    .right_item {
      width: 30%;
      position: absolute;
      top: 50%;
      right: 0;
      text-align: center;
    }
  }
}

.bottom_box {
  border-top: 1px solid #ccc;
  // position: absolute;
  // bottom: 0;
  width: 100%;
  height: 60px;
  background: #fff;
  display: flex;
  justify-content: left;
  align-items: center;
  padding: 0 20px;
}
.t {
  &::before {
    content: "*";
    color: red;
    margin-right: 5px;
  }
}
.ml8 {
  margin-left: 8px;
}
.title1 {
  font-size: 12px;
  font-weight: normal;
  margin-right: 20px;
}
</style>
